package com.shigen.demo.ForkJoinDemo;

import cn.hutool.core.date.StopWatch;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lombok.SneakyThrows;

/**
 * @author shigenfu
 * @date 2024/4/8 16:53
 */
public class ThreadPoolDemo {

    @SneakyThrows
    public static void main(String[] args) {
        int[] arr = new int[10_0000];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i + 1;
        }

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        ExecutorService executor = Executors.newFixedThreadPool(10);
        int sum = 0;
        int chunkSize = arr.length / 10;

        for (int i = 0; i < 10; i++) {
            int start = i * chunkSize;
            int end = (i == 9) ? arr.length : (start + chunkSize);
            sum += executor.submit(new SumTask(arr, start, end)).get();
        }

        executor.shutdown();
        stopWatch.stop();
        System.out.println("Sum of 1 to 100000 is: " + sum);
        System.out.println("代码执行时间：" + stopWatch.getLastTaskTimeMillis() + "毫秒");

    }
}

class SumTask implements Callable<Integer> {

    private final int[] arr;
    private final int start;
    private final int end;

    public SumTask(int[] arr, int start, int end) {
        this.arr = arr;
        this.start = start;
        this.end = end;
    }

    @Override
    public Integer call() {
        int sum = 0;
        for (int i = start; i < end; i++) {
            sum += arr[i];
        }
        return sum;
    }
}
